﻿using System;
using System.Linq;
using Diploma.Models.IRepositories;

namespace Diploma.Models.Repositories
{
    internal class MessagesRepository : IMessagesRepository
    {
        private readonly DiplomaEntities dataContext;

        public MessagesRepository(DiplomaEntities dataContext)
        {
            this.dataContext = dataContext;
        }

        public Message GetMessage(Guid id)
        {
            return dataContext.Messages.Where(m => m.MessageId == id && m.DeletionDate == null).FirstOrDefault();
        }

        public void Send(CollaborationRoom room, User user, string messageText)
        {
            if (String.IsNullOrWhiteSpace(messageText))
                throw new Exception();
            var message = new Message
                              {
                                  PubDate = DateTime.Now,
                                  CollaborationRoom = room,
                                  User = user,
                                  Text = messageText,
                                  MessageId = Guid.NewGuid(),
                              };
            dataContext.AddToMessages(message);
            dataContext.SaveChanges();
        }

        public void Delete(Message message)
        {
            message.DeletionDate = DateTime.Now;
            dataContext.SaveChanges();
        }
    }
}